<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

input {
  padding: 0 0 0 1px;
  width: 70%;
  margin-left: 10px;
}

textarea {
  width: 70%;
  height: 70px;
  margin-left: 10px;
  padding: 1px 0 0 2px;
}


</style>

<template>
  <!-- border: 1px solid blue -->
  <div style=" padding: 10px;height: 75vh;width: 100%;box-sizing: border-box">

    <!-- 搜索区域 -->
    <div style="margin: 0 0 10px 1px">
      <el-input @keyup="Load" v-model="data.SearchKeyWord" maxlength="30" placeholder="请输入关键字（仅文件名和文件类型可查）"
                style="width: 23%"
                clearable></el-input>
      <el-button style="margin-left: 10px" type="primary" @click="data.noticeDialogVisible = true">添加公告</el-button>
      <el-button
          type="danger"
          style="margin-left: 10px"
          @click="handleBatchDelete"
          :disabled="data.selectedRows.length === 0">
        批量删除
      </el-button>
    </div>

    <!--  表格  -->
    <!-- header-cell-style设置头部居中；cell-style设置单元格内容居中;stripe斑马纹 -->
    <!--  sortable实现排序按钮  -->
    <el-table
        :data="data.tableData"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        border
        stripe
        style="width: 98%; border-radius: 5px;margin-left: 1%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column fixed type="selection" sortable prop="noticeId" width="100" label="公告ID"/>
      <el-table-column sortable prop="noticeTitle" width="280" label="标题"/>
      <el-table-column sortable prop="noticeContent" width="520" label="公告内容"/>
      <el-table-column sortable prop="username" width="150" label="发布者"/>
      <el-table-column sortable prop="noticePublishTime" width="280" label="发布时间"/>
      <el-table-column sortable prop="isDeleted" width="180" label="状态" min-width="100">
        <template #default="scope">
          <span :style="scope.row.isDeleted !== 0 ? { 'font-weight': 'bold' } : {}">
            {{ scope.row.isDeleted === 0 ? '公开中' : '隐藏中' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column sortable fixed="right" label="操作" min-width="230">
        <template #default="scope">
          <el-button link type="primary" @click="handleEdit(scope.row)" :icon="Edit">
            编辑
          </el-button>
          <el-popconfirm title="确定永久删除吗?" v-model="scope.visible" @confirm="handleDelete(scope.row.noticeId)">
            <template v-slot:reference>
              <el-button type="primary" link :icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!--  分页  -->
    <el-pagination
        v-model:current-page="data.currentPage"
        v-model:page-size="data.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 1%"
    ></el-pagination>

    <div style="margin: 10px 0">
      <!--更新公告的弹框-->
        <!--   centerDialogVisible是一个变量，需要在script中定义一下，默认为false     -->
        <el-dialog v-model="data.centerDialogVisible" title="请输入更新的公告信息" width="30%" center style="margin-top: 150px">
          <el-form :model="data.form" label-width="60px" ref="fileTableFormRef">
            <el-form-item style="margin-left: 50px" label="标 题">
              <el-input v-model="data.form.noticeTitle" style="width: 80%;" placeholder="请输入公告标题"/>
            </el-form-item>

            <el-form-item style="margin-left: 50px" label="内 容">
              <el-input type="textarea" v-model="data.form.noticeContent" :rows="5" style="width: 80%;"
                        placeholder="请输入公告内容"/>
            </el-form-item>
            <el-form-item style="margin-left: 50px" label="状 态">
                <div class="mb-2 flex items-center text-sm" style="margin-left: 30px">
                  <el-radio-group v-model="data.form.isDeleted" class="ml-4">
                    <el-radio :label="1">隐 藏</el-radio>
                    <el-radio :label="0">公 开</el-radio>
                  </el-radio-group>
                </div>
            </el-form-item>
          </el-form>

          <template #footer>
            <span class="dialog-footer">
              <el-button @click="data.centerDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="save">确认</el-button>
            </span>
          </template>
        </el-dialog>


      <!--添加公告的弹框-->
        <!--   noticeDialogVisible是一个变量，需要在script中定义一下，默认为false     -->
        <el-dialog v-model="data.noticeDialogVisible" title="请输入添加的公告信息" width="30%" center style="margin-top: 150px">
          <el-form>
            <el-form-item style="margin-left: 50px" label="标 题">
              <el-input v-model="data.addForm.noticeTitle" style="width: 80%;" placeholder="请输入公告标题"/>
            </el-form-item>

            <el-form-item style="margin-left: 50px" label="内 容">
              <el-input type="textarea" v-model="data.addForm.noticeContent" :rows="5" style="width: 80%;"
                        placeholder="请输入公告内容"/>
            </el-form-item>
          </el-form>

          <template #footer>
            <span class="dialog-footer">
              <el-button @click="data.noticeDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="addNoticeSave">确认</el-button>
            </span>
          </template>
        </el-dialog>


      </div>
  </div>

  <div style="height: 8vh;">

  </div>
</template>

<script setup>
import {reactive, ref,} from "vue";
import {Delete, Edit} from '@element-plus/icons-vue'
import request from "../utils/request.js";
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus';
import {mainStore} from "@/stores/main.js";
import {useRouter} from "vue-router";

const Store = mainStore();
const router = useRouter();
const dataString = localStorage.getItem('data');
// 通过JSON.parse转换字符串为对象
const userLoginData = dataString ? JSON.parse(dataString) : null;

const fileTableFormRef = ref();
const data = reactive({
  //弹窗默认关闭
  centerDialogVisible: false,
  noticeDialogVisible: false,
  //当前页
  currentPage: 1,
  //每页多少条数据
  pageSize: 5,
  //搜索输入框
  SearchKeyWord: "",
  //数据条数
  total: 0,
  //表格数据
  tableData: [],
  selectedRows: [], // 选中行的数组
  //编辑表单
  form: {
    noticeId: "",
    noticeTitle: "",
    noticeContent: "",
    isDeleted: ""
  },
  addForm: {
    userId: null,
    noticeTitle: "",
    noticeContent: "",
  },
});


const Load = () => {
  let loadingInstance = ElLoading.service({fullscreen: true}); // 启动全屏加载动画
  console.log("搜索框关键词：", data.SearchKeyWord);

  request.get(`/java/notice/getAll?current=${data.currentPage}&size=${data.pageSize}&SearchKeyWord=${data.SearchKeyWord}`)
      .then((response) => {
        console.log("公告管理数据：", response);
        data.tableData = response.data.records;
        data.total = response.data.total;
      })
      .catch((error) => {
        console.error('请求发生错误:', error);
      })
      .finally(() => {
        loadingInstance.close();
      });
};

Load()

//改变分页大小
const handleSizeChange = (pageSize) => {
  data.currentPage = 1
  data.pageSize = pageSize
  Load()
}

//去到第几页
const handleCurrentChange = (currentPage) => {
  data.currentPage = currentPage
  Load()
}

//删除
const handleDelete = async (noticeId) => {
  try {
    const res = await request.delete("/java/notice/deleteById/" + noticeId);
    if (res.code === 200) {
      ElMessage({
        message: res.data,
        type: 'success',
      })
      data.centerDialogVisible = false
      Load()
    } else {
      ElMessage({
        message: res.data,
        type: 'error',
      })
    }
  } catch (e) {
    ElMessage.error(e)
  }

  handleCurrentChange(1);
};

//编辑
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));//让form对象独立出来，还能包含那一行的数据
  data.centerDialogVisible = true;
};


const handleSelectionChange = (selected) => {
  data.selectedRows = selected;
};

const handleBatchDelete = async () => {
  const selectedIds = data.selectedRows.map(row => row.noticeId);
  if (selectedIds.length === 0) {
    console.warn('没有选中任何行');
    return;
  }
  console.log('选中的行ID：', selectedIds);

  // 确认是否删除
  const confirmDelete = await ElMessageBox.confirm(
      '确定永久删除选中的行吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  );

  if (confirmDelete) {
    // 执行批量删除操作
    try {
      const res = await request.delete('/java/notice/delete/' + selectedIds);
      if (res.data){
        ElMessage({
          message: '删除成功',
          type: 'success',
        })
      }else {
        ElMessage({
          message: '删除失败',
          type: 'error',
        })
      }
      // 刷新列表
      Load();
    } catch (error) {
      console.error('批量删除失败：', error);
    }
  }
};

const save = () => {
  console.log(data.form)
  request.put(`java/notice/update`, data.form).then((res) => {
    console.log(res)
    if (res.code === 200) {
      ElMessage({
        message: res.data,
        type: 'success',
      })
      data.centerDialogVisible = false
      Load()
    } else {
      ElMessage({
        message: res.data,
        type: 'error',
      })
      data.centerDialogVisible = false
    }
  })
}


const addNoticeSave = () => {
  data.addForm.userId = userLoginData.userId
  request.post(`java/notice/insert`, data.addForm).then((res) => {
    if (res.code === 200) {
      ElMessage({
        message: res.data,
        type: 'success',
      })
      data.noticeDialogVisible = false
      data.addForm.userId = null
      data.addForm.noticeTitle = null
      data.addForm.noticeContent = null
      Load()
    } else {
      ElMessage({
        message: res.data,
        type: 'error',
      })
      data.noticeDialogVisible = false
    }
  })
}

</script>
